<?php

namespace App\Http\Controllers\Third;

use App\Enum\CodeEnum;
use App\Enum\RedisEnum;
use App\Enum\ThirdEnum;
use App\Http\Controllers\Api\ApiBaseController;
use App\Http\Controllers\Controller;
use App\Lib\Jwt;
use App\Models\ThirdOrderAllModel;
use App\Services\ThirdService;
use App\Services\VillagerUserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class IndexController extends ApiBaseController
{
    public function getOrderInfo(Request $request)
    {
        try {
            $thirdOrderNo = $this->_validThirdOrderNo($request->order_no);
            $redisKey = sprintf(RedisEnum::R_THIRD_ORDER_SEARCH, $thirdOrderNo);
            $result = $this->_cacheableData($redisKey, RedisEnum::EXPIRE_TIME_DEFAULT, (new ThirdService()),'getOrderInfo', $thirdOrderNo,  $request);
            return success($result);
        }catch (\Exception $e){
            return fail(CodeEnum::ERROR, '获取数据失败:'.$e->getMessage());
        }
    }
    public function getToken(Request $request)
    {
        try {
            $platformCode = '';
            $platformSecret = '';
            foreach( ThirdEnum::THIRD_PLATFORMS as $key=> $row ){
                if( $row[0]== $request->platformId ){
                    $platformCode = $key;
                    $platformSecret = $row[1];
                }
            }
            if( empty($platformCode) ) throw new \Exception("异常");

            $result = Jwt::encodeThirdToken($platformCode,$platformSecret);
            return success(['token'=>$result, 'platform-code'=>$platformCode]);
        }catch (\Exception $e){
            return fail(CodeEnum::ERROR, '获取数据失败:'.$e->getMessage());
        }
    }
    private function _validThirdOrderNo($orderNo)
    {
        if(strlen($orderNo)>50 || empty($orderNo)){
            throw new \Exception("三方订单号异常");
        }
        return $orderNo;
    }
}
